from neopixel import NeoPixel
from machine import Pin
from micropython import const


# 定义全局变量
WS2812_LED_LEVEL = const(0x10)
WS2812_POWERON = const(1)
WS2812_POWEROFF = const(0)


class WS2812(object):
    G = 0xff
    R = 0
    B = 0
#    offset = 0
    status = WS2812_POWEROFF
    phase = 0
    ws2812_interval = 0
    def __init__(self, di,num,c_ch = 3,timing=1):
        self.di = di
        self.num = num
        self.np =  NeoPixel(di, num,c_ch,timing)
        
    def ws2812_LED_Cycle(self):
        if self.status == WS2812_POWEROFF:
            return;
        for i in range(self.num - 1):
            self.np[self.num -1 - i] = np[self.num - 2 - i]
            
        if self.phase < WS2812_LED_LEVEL:
            self.G = int(self.G - (0xff / WS2812_LED_LEVEL))
            self.R = int(self.R + (0xff / WS2812_LED_LEVEL))
            self.phase += 1
            if self.phase == WS2812_LED_LEVEL:
                self.G = 0
                self.R = 0xff
        elif self.phase < (WS2812_LED_LEVEL * 2):
            self.R = int(self.R - (0xff / WS2812_LED_LEVEL))
            self.B = int(self.B + (0xff / WS2812_LED_LEVEL))
            self.phase += 1        
            if self.phase == (WS2812_LED_LEVEL * 2):
                self.R = 0
                self.B = 0xff
        elif  self.phase < (WS2812_LED_LEVEL * 3):
            self.B = int(self.B - (0xff / WS2812_LED_LEVEL))
            self.G = int(self.G + (0xff / WS2812_LED_LEVEL))
            self.phase += 1        
            if self.phase == (WS2812_LED_LEVEL * 3):
                self.phase = 0
                self.B = 0
                self.G = 0xff
        self.np[0] = (self.G,self.R,self.B)
        self.np.write()   #点亮RGB灯
        return self.phase

    def ws2812_Change_Status(self):
        self.status ^= 1
        self.ws2812_Power(self.status)
            
    def ws2812_Power(self,power):
        self.status = power
        if self.status == WS2812_POWEROFF:
#            ble.send('LED is OFF.')
            self.np.fill((0,0,0))
            self.np.write()   #关闭RGB灯
        else :
#            ble.send('LED is ON')
            self.phase = self.ws2812_LED_Cycle()
            